﻿using System;
using Newtonsoft.Json;

namespace ZYing.LiquidThemeEngine.Locales
{
    public class LocalizableTextJsonConverter : JsonConverter<ILocalizableText>
    {
        public override void WriteJson(JsonWriter writer, ILocalizableText value, JsonSerializer serializer)
        {
            if (value is FixedLocalizableText fix)
            {
                writer.WriteValue(fix.Text);
            }
            else if (value is DictionaryLocalizableText dic)
            {
                writer.WriteStartObject();
                foreach (var item in dic)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteValue(item.Value);
                }
                writer.WriteEndObject();
            }
            else
            {
                throw new NotSupportedException();
            }
        }

        public override ILocalizableText ReadJson(JsonReader reader, Type objectType, ILocalizableText existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                return new FixedLocalizableText((string)reader.Value);
            }

            if (reader.TokenType == JsonToken.StartObject)
            {
                var dic = new DictionaryLocalizableText();
                string lang = string.Empty;
                while (reader.Read())
                {
                    if (reader.TokenType == JsonToken.EndObject)
                    {
                        break;
                    }

                    switch (reader.TokenType)
                    {
                        case JsonToken.PropertyName:
                            lang = (string)reader.Value;
                            break;
                        case JsonToken.String:
                            if (!string.IsNullOrWhiteSpace(lang)) dic[lang] = (string)reader.Value;
                            break;
                    }
                }

                return dic;
            }
            throw new NotSupportedException();
        }
    }
}
